package br.com.gae.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.jdo.PersistenceManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jdo.PersistenceManagerFactoryUtils;
import org.springframework.transaction.annotation.Transactional;

public abstract class DAOGenerico<T> {
	@Autowired
	public PersistenceManagerFactory pmf;
	
	@Transactional
	public void salvar(T entidade){
		PersistenceManagerFactoryUtils.getPersistenceManager(this.pmf, false).makePersistent(entidade);
	}
	
	@Transactional
	public List<T> consultar(){
		Class<T> tipo = getTipoDaEntidade();
		List<T> retorno = (List<T>) PersistenceManagerFactoryUtils.getPersistenceManager(this.pmf, false).newQuery(tipo).execute(); 
		return retorno;
		
	}
	
	@Transactional
	public void excluir(T entidade){
		PersistenceManagerFactoryUtils.getPersistenceManager(this.pmf, false).deletePersistent(entidade);
	}
	
	protected Class<T> getTipoDaEntidade() {
		Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		return clazz;
	}
}
